package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.cache.redis.service.RedisStringService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.dao.SysDictionaryDao;
import com.jcfk.system.dao.SysDictionaryItemDao;
import com.jcfk.system.domain.dto.SysDictionaryDTO;
import com.jcfk.system.domain.po.SysDictionary;
import com.jcfk.system.domain.po.SysDictionaryItem;
import com.jcfk.system.domain.query.SysDictionaryQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典 服务
 */
@Slf4j
@Service
public class SysDictionaryService extends BaseService<SysDictionaryDao, SysDictionary> {

    @Autowired
    private SysDictionaryItemDao sysDictionaryItemDao;
    /**
     * Redis 缓存键名
     */
    private static final String redisKeyName = "ServiceCache:SysDictionary";

    @Autowired
    private RedisStringService redisStringService;

    /**
     * 根据条件获取分页列表
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysDictionaryDTO> queryByPage(DataPage<SysDictionaryDTO> page, SysDictionaryQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @return List<SampleSimpleTableDTO>
     */
    public List<SysDictionaryDTO> getList() {
        // 查询条件
        QueryWrapper<SysDictionary> qw = new QueryWrapper<>();

        qw.lambda().eq(SysDictionary::getDeleted, 0);
        // 查询数据
        List<SysDictionary> list = super.list(qw);
        List<SysDictionaryDTO> dtoList = new ArrayList<>();
        for (SysDictionary po : list) {
            SysDictionaryDTO dto = new SysDictionaryDTO();
            BeanUtils.copyProperties(po, dto);

            dtoList.add(dto);
        }
        return dtoList;
    }

    /**
     * 根据主键获取单条数据
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysDictionaryDTO getItemById(String id) {
        // 查询数据
        SysDictionary item = this.baseMapper.selectById(id);
        SysDictionaryDTO dto = new SysDictionaryDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 插入对象
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysDictionaryDTO insert(SysDictionaryDTO dto) {
        // 默认数据
        this.setDefaultValue(dto);

        // 保存
        SysDictionary item = new SysDictionary();
        BeanUtils.copyProperties(dto, item);
        super.save(item);

        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 更新对象
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysDictionaryDTO update(SysDictionaryDTO dto) {
        // 默认数据
        this.setDefaultValue(dto);


        SysDictionary item = this.getById(dto.getId());
        SysDictionaryItem sysDictionaryItem = new SysDictionaryItem();
        sysDictionaryItem.setDictionaryCode(dto.getCode());
        QueryWrapper<SysDictionaryItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("dictionary_code", item.getCode());
        sysDictionaryItemDao.update(sysDictionaryItem, itemQueryWrapper);

        // 保存
        BeanUtils.copyProperties(dto, item);
        super.updateById(item);


        BeanUtils.copyProperties(item, dto);
        return dto;
    }

    /**
     * 校验合法性
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysDictionaryDTO dto) {
        Integer count = 0;
        QueryWrapper<SysDictionary> qw = new QueryWrapper<>();
        if (!StrUtil.isEmpty(dto.getId())) {
            qw.lambda().ne(SysDictionary::getId, dto.getId());
        }
        qw.lambda().eq(SysDictionary::getCode, dto.getCode());
        qw.lambda().eq(SysDictionary::getDeleted, 0);

        count = this.baseMapper.selectCount(qw);
        if (count > 0) {
            return RetResult.fail("字典编码已存在");
        }

        return RetResult.ok();
    }

    /**
     * 根据主键批量删除(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysDictionaryDTO dto) {

        QueryWrapper<SysDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        // 保存
        SysDictionary item = new SysDictionary();
        item.setDeleted(1);
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        int count = this.baseMapper.update(item, queryWrapper);
        List<SysDictionary> list = this.baseMapper.selectList(queryWrapper);

        List<String> codes = list.stream().map(SysDictionary::getCode).collect(Collectors.toList());

        QueryWrapper<SysDictionaryItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.in("dictionary_code", codes);

        SysDictionaryItem sysDictionaryItem = new SysDictionaryItem();
        sysDictionaryItem.setDeleted(1);
        sysDictionaryItem.setLastUpdatedUserId(SecurityUtils.getUserId());
        sysDictionaryItem.setLastUpdateTime(new Date());
        sysDictionaryItemDao.update(sysDictionaryItem, itemQueryWrapper);

        return count >= 0 ? true : false;
    }

    /**
     * 设置添加默认值
     *
     * @param dto 添加对象
     */
    public void setDefaultValue(SysDictionaryDTO dto) {
        if (StrUtil.isEmpty(dto.getCreatedUserId())) {
            dto.setCreatedUserId(SecurityUtils.getUserId());
            dto.setCreateTime(new Date());
        }
        dto.setLastUpdatedUserId(SecurityUtils.getUserId());
        dto.setLastUpdateTime(new Date());
        dto.setDeleted(0);
    }
}
